<template>
  <div>
    <img src="../assets/icons/png/myledger.png" alt="我的账本" class="logo-pic">
    <h1 class="text-3xl font-bold underline">
      Hello Myledger!
    </h1>
    <div class="login-area">
      <el-tabs v-model="activeName" @tab-click="handleClick" class="login-tab" :stretch="true">
        <el-tab-pane label="账号登录" name="first">
          <div class="account-login">
            <div class="input-div">账号：
              <el-input v-model="account" placeholder="请输入账号" clearable class="input1" size="mini"></el-input>
            </div>
            <div class="input-div">密码：
              <el-input v-model="password" placeholder="请输入密码" show-password class="input1" size="mini"></el-input>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="验证登录" name="second">
          <div class="account-login">
            <div class="input-div">
              <span style="width: 20%">手机号：</span>
              <el-input v-model="phone" placeholder="请输入手机号" clearable class="input1" size="mini"></el-input>
            </div>
            <div class="input-div">
              <span style="width: 20%">验证码：</span>
              <el-input v-model="verCode" placeholder="验证码" class="input2" size="mini"></el-input>
              <el-button size="mini" @click="send()" :disabled="isDisSend" class="send-but">{{ sendText }}</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-link type="primary" v-show="getPwd" class="get-pwd-link">找回密码</el-link>
      <div class="login-div">
        <el-button size="mini" type="primary" class="login-but" @click="login()">登录</el-button>
        <el-button size="mini" type="warning" plain class="clean-but" @click="() => registerVisible = true">新用户注册</el-button>
      </div>
    </div>
    <el-dialog
        custom-class="cardInfo"
        append-to-body
        title="注册"
        :visible.sync="registerVisible"
        width="90%"
        center
    >
      <el-form ref="form" :model="formRegister" :rules="formRules" label-width="80px" >
        <el-form-item label="账户" required prop="account">
          <el-input v-model="formRegister.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" required prop="password">
          <el-input v-model="formRegister.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" required prop="password2">
          <el-input v-model="formRegister.password2" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="warning" @click="register()" size="small">注 册</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {getVerCode} from "@/utils/common";
import router from "@/router";
import RegisterView from "@/views/register/RegisterView.vue";
import userApi from "@/api/userApi";

export default {
  data() {
    return {
      formRegister: {},
      formRules: {
        account: [
          { required: true, message: '请输入帐号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      },
      registerVisible: false,
      sendText: '发送',
      activeName: 'first',
      account: '',
      password: '',
      phone: '',
      verCode: '',
      sysVerCode: '',
      isDisSend: false,
      countdown: 60,
      getPwd: true,
    };
  },
  methods: {
    /**
     * tab切换
     */
    handleClick() {
      if (this.activeName == "first") {
        this.phone = '';
        this.verCode = '';
        this.getPwd = true;
      }
      if (this.activeName == "second") {
        this.account = '';
        this.password = '';
        this.getPwd = false;
      }
    },
    /**
     * 短信发送
     */
    send() {
      if (this.phone == "") {
        this.$message({
          message: '请输入手机号',
          type: 'error'
        });
        return;
      }
      this.isDisSend = true
      this.sysVerCode = getVerCode();
      this.$notify.info({
        title: '消息',
        message: "【我的账本】您有新的验证码信息 " + this.sysVerCode + ",请核对后使用！",
        duration: '10000'    // 存在十秒
      });
      // this.$message("【我的账本】您有新的验证码信息 " + this.sysVerCode + ",请核对后使用！")
      this.countdownTimer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
          this.sendText = this.countdown + "秒";
        } else {
          // 倒计时结束，重置倒计时和状态
          this.sendText = "发送";
          this.countdown = 60;
          this.isDisSend = false;
          clearInterval(this.countdownTimer); // 清除计时器
        }
      }, 1000);
    },
    /**
     * 登录
     */
    login() {
      if (this.activeName == "first") {
        if (this.account == "") {
          this.$message({
            message: '请输入账号',
            type: 'error'
          });
          return;
        } else if (this.password == "") {
          this.$message({
            message: '请输入密码',
            type: 'error'
          });
          return;
        }
        this.postRequest('/user/userLogin', {
          userId: this.account,
          password: this.password,
          loginType: 1
        })
            .then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  message: '登录成功',
                  type: 'success'
                });
                window.localStorage.setItem('token', res.data.data.token);
                window.localStorage.setItem('nowIndex', -1);
                window.localStorage.setItem('userId', res.data.data.user.userId);
                window.localStorage.setItem('avatar',res.data.data.user.avatar);
                window.localStorage.setItem('username',res.data.data.user.username);
                router.push("/index");
              } else {
                this.$message({
                  message: '账号或密码错误',
                  type: 'error'
                });
              }
            })
            .catch((error) => {
              this.$message({
                message: '账号或密码错误',
                type: 'error'
              });
            });
      }
      if (this.activeName == "second") {
        if (this.phone == "") {
          this.$message({
            message: '请输入手机号',
            type: 'error'
          });
          return;
        } else if (this.verCode == "") {
          this.$message({
            message: '请输入验证码',
            type: 'error'
          });
          return;
        }
        if (this.verCode == this.sysVerCode) {
          this.postRequest('/user/verCodeLogin', {
            phone: this.phone,
          })
              .then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '登录成功',
                    type: 'success'
                  });
                  window.localStorage.setItem('token', res.data.data.token);
                  window.localStorage.setItem('nowIndex', -1);
                  window.localStorage.setItem('userId', res.data.data.user.userId);
                  window.localStorage.setItem('avatar',res.data.data.user.avatar);
                  window.localStorage.setItem('username',res.data.data.user.username);
                  router.push("/index");
                } else {
                  this.$message({
                    message: '登录失败',
                    type: 'error'
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  message: '登录失败',
                  type: 'error'
                });
              })
        } else {
          this.$message({
            message: '验证码错误',
            type: 'error'
          });
        }
      }

    },
    // 注册
    register() {
      this.formRegister.userId = this.formRegister.account
      const param = Object.assign({}, this.formRegister)
      userApi.userRegister(param).then(res => {
        if(res.data.code === 200) {
          this.$message.success('注册成功')
          this.registerVisible = false
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    /**
     * 清空
     */
    clean() {
      if (this.activeName == "first") {
        this.account = "";
        this.password = "";
      } else {
        this.phone = "";
        this.verCode = "";
      }
    }

  }
}

</script>


<style scoped>
.logo-pic {
  width: 80px;
  margin-top: 150px;
}

.login-area {
  margin-top: 50px;
  width: 100%;
  //margin-left: 50%;
}

.login-tab {
  width: 200px;
  margin: auto;
}

.input-div {
  float: left;
}

.input1 {
  width: 130px;
  margin-top: 15px;
}

.input2 {
  width: 70px;
  margin-top: 15px;
}

.send-but {
  margin-left: 5px;
  width: 55px;
}

.login-div {
  margin-top: 30px;
}

.clean-but {
  left: 10px;
}

.get-pwd-link {
  float: right;
  margin-right: 100px;
  margin-top: 5px;
  font-size: 10px;
}

::v-deep .el-dialog--center .el-dialog__body{
  padding-bottom: 0!important;
}

</style>